/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.crm.cs.web.MemberMsgAction
   Module Description   :

   Date Created      : 2011/1/19
   Original Author   : cut7man
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.crm.cs.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.membermsg.entity.MemberMsg;
import com.yaodian100.ec.membermsg.entity.MemberMsgTemplate;
import com.yaodian100.ec.membermsg.service.MemberMsgService;

/**
 * @author cut7man
 * 
 */
public class MemberMsgAction {
	private MemberMsgTemplate template;
	private MemberMsg msg;
	private File file;
	private String errMsg;
	private String orders;
	@Resource
	private BaseManager baseMgr;
	@Resource
	private MemberMsgService msgService;
	@Resource
	private TemplateService velocityService;
	private String sendTime;
	private String type;
	private String tempId;
	private String sendTo;
	private Date sendDate;
	private String msgId;
	private String coupon;
	private String bonus;
	private String previewContent;

	/**
	 * @return the coupon
	 */
	public String getCoupon() {
		return coupon;
	}

	/**
	 * @param coupon the coupon to set
	 */
	public void setCoupon(String coupon) {
		this.coupon = coupon;
	}

	/**
	 * @return the bonus
	 */
	public String getBonus() {
		return bonus;
	}

	/**
	 * @param bonus the bonus to set
	 */
	public void setBonus(String bonus) {
		this.bonus = bonus;
	}

	/**
	 * @return the previewContent
	 */
	public String getPreviewContent() {
		return previewContent;
	}

	/**
	 * @param previewContent the previewContent to set
	 */
	public void setPreviewContent(String previewContent) {
		this.previewContent = previewContent;
	}

	/**
	 * @return the msgId
	 */
	public String getMsgId() {
		return msgId;
	}

	/**
	 * @param msgId the msgId to set
	 */
	public void setMsgId(String msgId) {
		this.msgId = msgId;
	}

	/**
	 * @return the tempId
	 */
	public String getTempId() {
		return tempId;
	}

	/**
	 * @param tempId the tempId to set
	 */
	public void setTempId(String tempId) {
		this.tempId = tempId;
	}

	/**
	 * @return the sendDate
	 */
	public Date getSendDate() {
		return sendDate;
	}

	/**
	 * @param sendDate the sendDate to set
	 */
	public void setSendDate(Date sendDate) {
		this.sendDate = sendDate;
	}

	/**
	 * @return the sendTime
	 */
	public String getSendTime() {
		return sendTime;
	}

	/**
	 * @param sendTime the sendTime to set
	 */
	public void setSendTime(String sendTime) {
		this.sendTime = sendTime;
	}

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}

	/**
	 * @return the orders
	 */
	public String getOrders() {
		return orders;
	}

	/**
	 * @param orders the orders to set
	 */
	public void setOrders(String orders) {
		this.orders = orders;
	}

	/**
	 * @return the errMsg
	 */
	public String getErrMsg() {
		return errMsg;
	}

	/**
	 * @param errMsg the errMsg to set
	 */
	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}

	/**
	 * @return the file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(File file) {
		this.file = file;
	}

	/**
	 * @return the msg
	 */
	public MemberMsg getMsg() {
		return msg;
	}

	/**
	 * @param msg the msg to set
	 */
	public void setMsg(MemberMsg msg) {
		this.msg = msg;
	}

	/**
	 * @return the template
	 */
	public MemberMsgTemplate getTemplate() {
		return template;
	}

	/**
	 * @param template the template to set
	 */
	public void setTemplate(MemberMsgTemplate template) {
		this.template = template;
	}

	public String list() {

		return "list";
	}

	public String toUpdate() {
		return "toUpdate";
	}

	public String preview() {
		String content = null;
		if (msgId != null && msgId.length() > 0) {
			MemberMsg msg = (MemberMsg) baseMgr.get(MemberMsg.class, Long.valueOf(msgId));
			content = msg.getContent();
		} else {
			template = (MemberMsgTemplate) baseMgr.get(MemberMsgTemplate.class, Long.valueOf(tempId));
			if (type.equals(MemberMsgTemplate.SEND_TYPE.MAIL.getValue())) {
				content = template.getMailContent();

			} else {
				content = template.getSmsContent();

			}
		}

		Map<String, Object> objs = new HashMap<String, Object>();
		objs.put("baseHref", ServerValue.getFrontHostname());
		previewContent = velocityService.formatByStringTemplate(content, objs);
		return "preview";
	}

	public String preResult() {
		try {
			if (file != null) {
				FileInputStream fis = new FileInputStream(file);
				BufferedReader bd = new BufferedReader(new InputStreamReader(fis));
				String line = "";
				List<String> orderList = new ArrayList<String>();
				while ((line = bd.readLine()) != null) {
					orderList.add(line);
					if (orders != null && orders.length() > 0) {
						orders += ",";
					}
					orders += line;
				}
				fis.close();
				bd.close();
			}
			if (orders != null) {
				Object[] results = baseMgr.queryByHql("from Option where code=? and menu.key=?", new Object[] {
						"msg_max_orders", "SystemValue" }, 0, 1);
				Option option = (Option) results[0];
				String[] orderArray = orders.split(",");
				if (orderArray.length > Integer.valueOf(option.getMemo1())) {
					throw new Exception("您上传实际笔数为：" + orderArray.length + "；笔数上限为：" + option.getMemo1() + "，请调整！");
				}
			}
			if (sendTime != null) {
				if (Integer.valueOf(sendTime) > 0) {
					Calendar calendar = Calendar.getInstance();
					calendar.add(Calendar.HOUR_OF_DAY, Integer.valueOf(sendTime));
					sendDate = calendar.getTime();
				}
			}
		} catch (Exception e) {
			errMsg = "预览时发生错误（" + e.getMessage() + "）";
		}
		return "preResult";
	}

	public String result() {
		try {
			if (file != null) {
				FileInputStream fis = new FileInputStream(file);
				BufferedReader bd = new BufferedReader(new InputStreamReader(fis));
				String line = "";
				List<String> orderList = new ArrayList<String>();
				while ((line = bd.readLine()) != null) {
					orderList.add(line);
					if (orders != null && orders.length() > 0) {
						orders += ",";
					}
					orders += line;
				}
				fis.close();
				bd.close();
			}
			if (orders != null) {
				Object[] results = baseMgr.queryByHql("from Option where code=? and menu.key=?", new Object[] {
						"msg_max_orders", "SystemValue" }, 0, 1);
				Option option = (Option) results[0];
				String[] orderArray = orders.split(",");
				if (orderArray.length > Integer.valueOf(option.getMemo1())) {
					throw new Exception("您上传实际笔数为：" + orderArray.length + "；笔数上限为：" + option.getMemo1() + "，请调整！");
				}
			}
			if (sendTime != null) {
				if (Integer.valueOf(sendTime) >= 0) {
					Calendar calendar = Calendar.getInstance();
					calendar.add(Calendar.HOUR_OF_DAY, Integer.valueOf(sendTime));
					sendDate = calendar.getTime();
				}
			} else {
				Calendar calendar = Calendar.getInstance();
				sendDate = calendar.getTime();
			}
			if (msg == null) {
				msg = new MemberMsg();
			}
			msg.setTempId(Long.valueOf(tempId));
			msg.setSendTime(sendDate);
			msg.setSuccess(orders);
			msg.setSendTo(sendTo);
			msg.setCreateDate(new Date());
			msg.setSendType(type);
			if (coupon != null && !coupon.equals("")) {
				msg.setCoupon(BigDecimal.valueOf(Double.valueOf(coupon)));
				msg.getCoupon().setScale(1, BigDecimal.ROUND_HALF_EVEN);
			}
			if (bonus != null && !bonus.equals("")) {
				msg.setBonus(BigDecimal.valueOf(Double.valueOf(bonus)));
				msg.getBonus().setScale(1, BigDecimal.ROUND_HALF_EVEN);
			}

			msg.setUnsuccess("");
			msg.setStatus(MemberMsg.STATUS.WAIT_FOR_SEND.getValue());
			msgService.saveMsg(msg);
		} catch (RuntimeException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			errMsg = "新建会员通知发生错误（" + e.getMessage() + "）";
		}
		return "list";
	}

	public String deleteMsg() {
		msgService.markDelete(Long.valueOf(msgId));
		return "list";
	}

	public String viewDetail() {
		msg = (MemberMsg) baseMgr.get(MemberMsg.class, Long.valueOf(msgId));
		return "result";
	}

	public String toUpdateTemplate() {
		return "toUpdateTemplate";
	}

	public String updateTemplate() {
		baseMgr.saveOrUpdate(template);
		return "updateTemplate";
	}

	public String templateList() {

		return "templateList";
	}

	public String getSendTo() {
		return sendTo;
	}

	public void setSendTo(String sendTo) {
		this.sendTo = sendTo;
	}

}
